
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Valve.Newtonsoft.Json;
using Valve.Newtonsoft.Json.Linq;

public class LoadAndSaveData 
{
    private static string multipleFilepath;
    
  
    //逐行写入
    public static void SaveToJsonFile<T>(List<T> parts, string path)
    {
        FileStream fs1 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs1);
        for (int i = 0; i < parts.Count; i++)
        {

            string str = JsonUtility.ToJson(parts[i]);
            sw.WriteLine(str);
        }
        sw.Flush();
        sw.Close();
        fs1.Close();
    }
    //逐行读取
    public static void LoadFromJsonFile<T>( List<T> dataList, string filePath)
    {
        StreamReader sr = new StreamReader(filePath);
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            T partsClass = JToken.Parse(line).ToObject<T>();
            dataList.Add(partsClass);
        }
        sr.Close();
    }

    /// <summary>
    /// 全部写入 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name=""></param>
    public static void SaveClassFile<T>(string path ,T data) {
        string json = JsonConvert.SerializeObject(data, Formatting.Indented);
        //FileStream fs1 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter sw = new StreamWriter(path,false);
        sw.Write(json);
        sw.Flush();
        sw.Close();
        //fs1.Close();
    }
    /// <summary>
    /// 全部读取
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static T LoadClassFile<T>(string path ) {
        StreamReader sr = new StreamReader( path );
        string line;
        while ((line = sr.ReadToEnd()) != null)
        {
            sr.Close();
            return  JsonConvert.DeserializeObject<T>(line);
        }
      
        return default;
    }
}
